#include <func.h>

int function(int fd)
{
    int status=fcntl(fd,F_GETFL);
    status=status|O_NONBLOCK;
    int ret=fcntl(fd,F_SETFL,status);
    ERROR_CHECK(ret,-1,"fcntl");
    return 0;
}

int main(int argc,char* argv[])
{
    ARGS_CHECK(argc,3);
    int sfd;
    sfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sfd,-1,"socket");
    int reuse=1,ret;
    ret=setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));
    ERROR_CHECK(ret,-1,"setsockopt");
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family=AF_INET;
    ser_addr.sin_addr.s_addr=inet_addr(argv[1]);
    ser_addr.sin_port=htons(atoi(argv[2]));
    ret=bind(sfd,(struct sockaddr*)&ser_addr,sizeof(ser_addr));
    ERROR_CHECK(ret,-1,"bind");
    ret=listen(sfd,10);
    ERROR_CHECK(ret,-1,"listen");
    int new_fd;
    struct sockaddr_in cli_addr;
    bzero(&cli_addr,sizeof(cli_addr));
    socklen_t cli_len=sizeof(cli_addr);
    new_fd=accept(sfd,(struct sockaddr *)&cli_addr,&cli_len);
    ERROR_CHECK(new_fd,-1,"accept");
    printf("client ip=%s,client port=%d\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
    char buf[32]={0};
    int epfd=epoll_create(1);//这个epoll就相当于帮你封装了一个过程，
    struct epoll_event event,evs[2];
    event.data.fd=STDIN_FILENO;
    event.events=EPOLLIN;
    ret=epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event);//将STDIN加入检测里，当二者有一个有数据，epfd都会检测到，并且将其中的数据给到evs[0]。
    ERROR_CHECK(ret,-1,"epoll_ctl");
    function(new_fd);
    event.data.fd=new_fd;
    event.events=EPOLLIN;
    ret=epoll_ctl(epfd,EPOLL_CTL_ADD,new_fd,&event);
    ERROR_CHECK(ret,-1,"epoll_ctl");
    int ready_num,i;
    while (1)
    {
        ready_num=epoll_wait(epfd,evs,2,-1);
        for(i=0;i<ready_num;i++)
        {
            if(evs[i].data.fd==STDIN_FILENO)
            {
                bzero(buf,sizeof(buf));
                ret=read(STDIN_FILENO,buf,sizeof(buf));                
                if(!ret)
                {
                    printf("i want to go\n");
                    return 0;
                }
                send(new_fd,buf,strlen(buf)-1,0);
            }
            while(1)
            {
                if(evs[i].data.fd==new_fd)
                {
                    bzero(buf,sizeof(buf));
                    ret=recv(new_fd,buf,sizeof(buf)-1,0);
                    if(!ret)
                    {
                        printf("byebye\n");
                        return 0;
                    }
                    else if(-1==ret)
                    {
                        printf("\n");
                        break;
                    }
                    else
                    {
                        printf("%s",buf);
                    }
                }
            }
        }
    }
    close(new_fd);
    close(sfd);
    return 0;
}